package com.metadata_system.common.utils;

import com.metadata_system.common.dto.ApiResult;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class HttpUtil {
    public static ApiResult httpPost(String httpUrl, MultiValueMap<String, Object> httpParams) {
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(httpParams, headers);
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
//        System.out.println("httpUrl: "+httpUrl);
        try {
            ResponseEntity<String> response = client.exchange(httpUrl, method, requestEntity, String.class);
            return ApiResult.success(response.getBody());
        }catch (Exception e){
            return ApiResult.error(e.getMessage());
        }
    }


    public static ApiResult httpJSONPost(String httpUrl, String jsonString) {
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<String>(jsonString, headers);

        // 请求获取响应
        try {
            String responseBody = client.postForObject(httpUrl, request, String.class);
            return ApiResult.success(responseBody);
        }catch (Exception e){
            return ApiResult.error(e.getMessage());
        }
    }


    public static ApiResult httpGet(String httpUrl) {
        RestTemplate client = new RestTemplate();
        ResponseEntity<String> res = client.getForEntity(httpUrl, String.class);
        return ApiResult.success(res.getBody());
    }
}
